package com.ctyon.watchmanager.ui.fragment;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.bean.AlarmBean;
import com.ctyon.watchmanager.databinding.FragmentAlarmBinding;
import com.ctyon.watchmanager.dialog.AlarmDialog;
import com.ctyon.watchmanager.listener.ItemClickListener;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.AlarmPresenter;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.ctyon.watchmanager.ui.adapter.AlarmsAdapter;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class AlarmFragment extends BaseFragment {

    public static final String TAG = "AlarmFragment";

    private FragmentAlarmBinding mBinding;
    private AlarmsAdapter mAdapter;
    private final String[] alarmArr = new String[3];
    private String alarms;
    private List<AlarmBean> alarmList = new ArrayList<>();
    private AlarmDialog dialog;
    private AlarmBean alarmBean;
    private int mIndex = -1;

    public static AlarmFragment newInstance() {
        final AlarmFragment fragment = new AlarmFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_alarm, container, false);
        mBinding.setAlarmPresenter(alarmPresenter);

        mAdapter = new AlarmsAdapter(itemClickListener);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mBinding.alarmRecycle.setLayoutManager(layoutManager);
        mBinding.alarmRecycle.setAdapter(mAdapter);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        alarms = BasicApp.getInstance().getWatch().getAlarms();
        if (!DataUtil.isEmptyAnd(alarms) && alarms.contains("*")) {
            String[] strings = alarms.split("&");
            for (int i = 0; i < (strings.length < 3 ? strings.length : 3); i++) {
                alarmArr[i] = strings[i];
            }
            loadAlarms();
        }

    }

    private void loadAlarms() {
        for (String s : alarmArr) {
            if (DataUtil.isEmptyAnd(s)) {
                continue;
            }
            AlarmBean alarmBean = new AlarmBean(s);
            alarmList.add(alarmBean);
        }
        if (alarmList.size() > 0) {
            mBinding.setIsEmpty(false);
        }
        mAdapter.setAlarmList(alarmList);
    }

    private final ItemClickListener<Integer> itemClickListener = new ItemClickListener<Integer>() {
        @Override
        public void onItemClick(Integer index) {
            Logger.d("onItemClick : index = " + index);
            mIndex = index;
            showPicker();
            AlarmBean alarm = alarmList.get(index);
            String[] s = alarm.getTime().split(":");
            dialog.setTime(Integer.valueOf(s[0]), Integer.valueOf(s[1]), alarm.getType(), alarm.getDays());
        }

        @Override
        public void onSwitchClick(int position, boolean isChecked) {
            Logger.d("onSwitchClick : position = " + position + "  isChecked = " + isChecked);
            List<AlarmBean> alarmBeans = new ArrayList<>();
            alarmBeans.addAll(alarmList);
            alarmBeans.get(position).setState(isChecked ? 1 : 0);
            uploadAlarms(alarmBeans);
        }
    };

    private final AlarmPresenter alarmPresenter = () -> {
        if (alarmList.size() >= 3) {
            TSnackbarUtil.TSBError(getActivity(), "最多只能添加三个闹钟");
            return;
        }
        showPicker();
    };

    private final AlarmDialog.AlarmPickerCallback alarmPickerCallback = alarm -> {
        alarmBean = new AlarmBean(alarm);
        Logger.t(LTAG).i("alarm ： " + alarmBean.toString());
        if (mBinding.getIsEmpty()) {
            mBinding.setIsEmpty(false);
        }
        if (!DataUtil.isEmptyAnd(BasicApp.getInstance().getWatch().getAlarms()) && BasicApp.getInstance().getWatch().getAlarms().contains(alarmBean.toString())) {
            TSnackbarUtil.TSBError(getActivity(), "已存在");
            return;
        }
        List<AlarmBean> alarmBeans = new ArrayList<>();
        alarmBeans.addAll(alarmList);
        if (mIndex == -1) {
            alarmBeans.add(alarmBean);
        } else {
            alarmBeans.set(mIndex, alarmBean);
        }
        uploadAlarms(alarmBeans);
    };

    private void showPicker() {
        if (null == dialog) {
            Logger.t(LTAG).i("Create Dialog");
            dialog = new AlarmDialog(getActivity(), R.style.CustomDialog);
            dialog.setAlarmPickerCallback(alarmPickerCallback);
            Window window = dialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setWindowAnimations(R.style.CustomDialogStyle);
        }
        dialog.show();
    }

    private void uploadAlarms(List<AlarmBean> alarmBeans) {
        final StringBuilder alarmData = new StringBuilder();
        Logger.t(LTAG).d("alarmData size = " + alarmBeans.size());
        if (alarmBeans.size() == 0) {
            return;
        }
        for (int i = 0; i < alarmBeans.size(); i++) {
            if (i > 0) {
                alarmData.append("&");
            }
            alarmData.append(alarmBeans.get(i).toString());
        }
        String data = alarmData.toString().replace(":", "*");
        Logger.t(LTAG).d("alarmData : " + data);

        final String method = "alarm";
        if (NetService.getInstance().isDisable(method)) {
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .method(method)
                .alarm(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid(), data)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "操作成功");
                        alarmList.clear();
                        alarmList.addAll(alarmBeans);
                        mAdapter.setAlarmList(alarmList);
                        BasicApp.getInstance().getWatch().setAlarms(data);
                    }

                    @Override
                    public String onOver() {
                        mIndex = -1;
                        return method;
                    }
                });
    }

}
